import axios from 'axios'
import { useMain,store } from "../store/index";
import { getUserRefreshToken, deleteCookie } from "../utils/utils"
import router from "../routes/index"
// import { createPinia } from 'pinia'

// const pinia = createPinia()

const downLoadAxios = axios.create();//新建一个axios实例
downLoadAxios.defaults.timeout = 15000;
if (import.meta.env.VITE_ENV != 'production') {
    downLoadAxios.defaults.baseURL= import.meta.env.VITE_BASE_API
} else {
    downLoadAxios.defaults.baseURL = location.origin;
}
// downLoadAxios.defaults.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'; 
downLoadAxios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8';
// axios.defaults.responseType= 'bolb'; 

let loading: any = null;

// const useMainStore = useMain(pinia);
const useMainStore = useMain(store);
//请求拦截器
downLoadAxios.interceptors.request.use((config) => {
    // console.log('config',config.url);

    // console.log('useMain',useMainStore.authToken);
    // config.responseType= 'bolb'; 
    const token = useMainStore.authToken ? useMainStore.authToken : '';
    const currentProjectInfo: any = useMainStore.currentProjectInfo ? useMainStore.currentProjectInfo : {};
    if (token) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Authorization'] = token;
    }
    if (currentProjectInfo && currentProjectInfo.projectId) {
        // 在发起请求前，给所有请求的头部添加token
        config.headers['Project-Id'] = currentProjectInfo.projectId;
    }
     //平台类型
     config.headers['Platform-Type'] = 3;
    //当请求刷新令牌接口时,请求头Authorization替换为之前的refreshToken
    if (config.url == '/user/auth/refreshToken' && useMainStore.refreshToken) {
        config.headers['Authorization'] = useMainStore.refreshToken;
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

//判断字符串是否可以转成json格式
function isValidJSON(str: any) {
    try {
        JSON.parse(str);
        return true;
    } catch (error) {
        return false;
    }
}

//解析字符串封装成promise
function readMyFile(file: any) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsText(file);
        //   reader.onload = e => resolve(e!.target.result);
        reader.onload = (e: any) => {
            const text: any = reader.result;

            // 解析字符串为 JSON 格式
            if (isValidJSON(text)) {
                resolve(e.target.result);
            } else {
                resolve(null);
            }
        }
        reader.onerror = (e: any) => {
            reject(e);
        }

    });
}

//响应拦截器
downLoadAxios.interceptors.response.use(async (response: any): Promise<any> => {
    // loading && loading.close();//关闭loading
    // loading = null;//清空loading
    let res = response.data;
    // let res = response;
    if (!response.data) {
        res = response;
    }
    const data: any = await readMyFile(res);
    // console.log('data', JSON.parse(data).resultCode)
    if (data && JSON.parse(data) && JSON.parse(data).resultCode) {
        let resultCode = JSON.parse(data).resultCode;
        let resultMsg = JSON.parse(data).resultMsg;
        if (resultCode) {
            if (res && resultCode === '200' || resultCode === '201') {//请求成功时的处理
                return Promise.resolve(res);
            } else if (res && (resultCode === '403' || resultCode === '403-2' || resultCode === '403-3' || resultCode === '403-4' || resultCode === '403-5' || resultCode === '403-6')) {
                // window.location.href = "/login";
                //清空登录信息
                useMainStore.updatedAuthToken("");
                useMainStore.updatedRefreshToken("");
                useMainStore.updatedUserInfo({});
                deleteCookie("authToken");
                deleteCookie("refreshToken");
                router.push('/login');
            } else {//请求失败时的处理

                ElMessage({
                    message: resultMsg ? resultMsg : "连接超时,请稍后重试",
                    grouping: true,
                    type: 'error',
                })
            }

        }
        return Promise.reject(res)
    } else {
        return Promise.resolve(res);
    }
}, async (error) => {
    if (error.response && error.response.data) {
        const data: any = await readMyFile(error.response.data);
        if (data && JSON.parse(data) && JSON.parse(data).resultCode) {
            let resultCode = JSON.parse(data).resultCode;
            let resultMsg = JSON.parse(data).resultMsg;
            if (resultCode == '403-1') {
                await getUserRefreshToken();
                return downLoadAxios(error.config)
            } else if (resultCode === '403' || resultCode === '403-2' || resultCode === '403-3' || resultCode === '403-4' || resultCode === '403-5' || resultCode === '403-6') {
                //清空登录信息
                useMainStore.updatedAuthToken("");
                useMainStore.updatedRefreshToken("");
                useMainStore.updatedUserInfo({});
                deleteCookie("authToken");
                deleteCookie("refreshToken");
                router.push('/login');
            }else{
                ElMessage({
                    message: resultMsg ? resultMsg : "连接超时,请稍后重试",
                    grouping: true,
                    type: 'error',
                })
            }
        } else {
            ElMessage({
                message: "连接超时,请稍后重试",
                grouping: true,
                type: 'error',
            })
        }
    } else {

        ElMessage({
            message: "连接超时,请稍后重试",
            grouping: true,
            type: 'error',
        })
    }
    // console.log('error',error.response.data);
    // loading && loading.close();//关闭loading
    // loading = null;//清空loading
    return Promise.reject(error)
})

export default downLoadAxios

/**
* 封装get方法
* @param url
* @param params
* @returns {Promise}
*/

export function get_downLoad(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        downLoadAxios.get(url, {
            params: params,
            responseType: "blob",
        })
            .then(response => {
                resolve(response)
            })
            .catch(err => {

                reject(err)
            })
    })
}

/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/

export function post_downLoad(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        downLoadAxios.post(url, data)
            .then(response => {
                resolve(response)
            }, err => {
                reject(err)
            })
    })
}

/**
* 封装delete方法
* @param url
* @param params
* @returns {Promise}
*/

export function doDelete_downLoad(url: any, params: Object = {}) {
    return new Promise((resolve, reject) => {
        downLoadAxios.delete(url, {
            params: params
        })
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/

export function patch_downLoad(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        downLoadAxios.patch(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/

export function put_downLoad(url: any, data: Object = {}) {
    return new Promise((resolve, reject) => {
        downLoadAxios.put(url, data)
            .then(response => {
                resolve(response.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}